// 发布页面逻辑
Page({
  data: {
    dong: '',
    describe: '',
    image: [],
    avatarUrl: '',
    nickName: '',
    createTime: ''
  },
  onLoad: function () {
    // 检查用户是否已登录
    const userInfo = wx.getStorageSync('userinfo');
    if (!userInfo || !userInfo.avatarUrl) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      wx.navigateTo({
        url: '/pages/login/login'
      });
      return;
    }

    this.setData({
      avatarUrl: userInfo.avatarUrl,
      nickName: userInfo.nickName
    });
    console.log('发布页面获取的 avatarUrl:', this.data.avatarUrl);
  },
  // 处理栋数输入变化
  handleDongInputChange(e) {
    this.setData({
      dong: e.detail.value
    });
  },
  // 处理物品描述输入变化
  handleDescribeInputChange(e) {
    this.setData({
      describe: e.detail.value
    });
  },
  // 压缩图片
  compressImage: function (tempFilePath) {
    return new Promise((resolve, reject) => {
      wx.compressImage({
        src: tempFilePath,
        quality: 80,
        success: res => resolve(res.tempFilePath),
        fail: err => resolve(tempFilePath) // 如果压缩失败，使用原图
      });
    });
  },

  // 上传单张图片（带重试机制）
  uploadSingleImage: async function (tempFilePath, retryCount = 3) {
    const cloudPath = `images/${Date.now()}-${Math.random() * 1000000}.${tempFilePath.split('.').pop()}`;

    for (let i = 0; i < retryCount; i++) {
      try {
        const uploadRes = await Promise.race([
          wx.cloud.uploadFile({
            cloudPath,
            filePath: tempFilePath
          }),
          new Promise((_, reject) =>
            setTimeout(() => reject(new Error('上传超时')), 30000)
          )
        ]);
        return uploadRes.fileID;
      } catch (err) {
        console.error(`第${i + 1}次上传失败:`, err);
        if (i === retryCount - 1) throw err;
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); // 递增延迟重试
      }
    }
  },

  // 选择图片并上传至云存储
  chooseImage: async function () {
    try {
      const res = await wx.chooseImage({
        count: 9,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      });

      wx.showLoading({ title: '正在处理图片...' });

      const tempFilePaths = res.tempFilePaths;
      const cloudPaths = [];
      let failCount = 0;

      // 并发处理所有图片
      const uploadTasks = tempFilePaths.map(async (tempFilePath) => {
        try {
          // 先压缩图片
          const compressedPath = await this.compressImage(tempFilePath);
          // 上传压缩后的图片
          const fileID = await this.uploadSingleImage(compressedPath);
          cloudPaths.push(fileID);
        } catch (err) {
          console.error('图片处理失败:', err);
          failCount++;
        }
      });

      await Promise.all(uploadTasks);
      wx.hideLoading();

      if (cloudPaths.length > 0) {
        this.setData({
          image: this.data.image.concat(cloudPaths)
        });

        if (failCount > 0) {
          wx.showToast({
            title: `${failCount}张图片上传失败，请重试`,
            icon: 'none',
            duration: 2000
          });
        } else {
          wx.showToast({
            title: '图片上传成功',
            icon:'success'
          });
        }
      } else {
        wx.showToast({
          title: '图片上传失败，请检查网络后重试',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (err) {
      wx.hideLoading();
      wx.showToast({
        title: '图片选择失败，请检查网络或权限',
        icon: 'none'
      });
    }
  },
  // 删除图片
  deleteImage: function (e) {
    const index = e.currentTarget.dataset.index;
    const image = this.data.image;
    image.splice(index, 1);
    this.setData({
      image: image
    });
  },
  // 验证栋数
  validateDong(dong) {
    if (!dong) {
      return '栋数不能为空';
    }
    const num = parseInt(dong, 10);
    if (isNaN(num) || num < 1 || num > 18) {
      return '栋数必须是 1 - 18 之间的整数';
    }
    return null;
  },
  // 验证物品描述
  validateDescribe(describe) {
    if (!describe) {
      return '物品描述不能为空';
    }
    // 可以添加更多验证逻辑，如长度限制等
    return null;
  },
  // 发布函数，将物品信息和图片信息关联保存到云数据库
  publishItem: async function () {
    const { dong, describe, image, avatarUrl, nickName } = this.data;
    const dongError = this.validateDong(dong);
    if (dongError) {
      wx.showToast({ title: dongError, icon: 'none' });
      return;
    }
    const describeError = this.validateDescribe(describe);
    if (describeError) {
      wx.showToast({ title: describeError, icon: 'none' });
      
      return;
    }

    // 当未选择图片时，弹出确认框
    if (image.length === 0) {
      try {
        const confirmResult = await new Promise((resolve) => {
          wx.showModal({
            title: '提示',
            content: '您未选择图片，是否继续发布？',
            success: (res) => {
              resolve(res.confirm);
            }
          });
        });

        if (!confirmResult) {
          return;
        }
      } catch (err) {
        console.error('确认框出现错误:', err);
        return;
      }
    }

    try {
      // 在栋数后面添加“栋”字
      const formattedDong = `${dong}栋`;

      // 保存数据到云数据库
      const db = wx.cloud.database();
      const res = await db.collection('loudong').add({
        data: {
          dong: formattedDong,
          describe,
          image,
          avatarUrl,
          nickName,
          createTime: new Date()
        }
      });
      wx.showToast({ title: '发布成功', icon:'success' });
      // 清空页面数据
      this.setData({
        dong: '',
        describe: '',
        image: [],
        createTime: ''
      });
    } catch (err) {
      console.error('发布失败:', err);
      wx.showToast({ title: '发布失败，请稍后再试', icon: 'none' });
    }
  },
  // 跳转至已发布界面
  navigateToQueryPage: function () {
    wx.navigateTo({
      url: '/pages/query/query' // 替换为实际的已发布界面路径
    });
  }
})